<template>
  <div class="herb-category-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>药材分类管理</span>
          <div>
            <el-button type="primary" @click="handleAdd">新增分类</el-button>
            <el-button @click="loadCategoryTree">刷新</el-button>
          </div>
        </div>
      </template>

      <div class="search-form" v-if="showSearch">
        <el-form :model="searchForm" inline>
          <el-form-item label="分类名称">
            <el-input v-model="searchForm.categoryName" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="text" @click="toggleSearch">
              {{ showSearch ? '隐藏搜索' : '显示搜索' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <div style="margin-bottom: 16px;">
        <el-radio-group v-model="viewMode">
          <el-radio-button label="tree">树形视图</el-radio-button>
          <el-radio-button label="table">表格视图</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 树形视图 -->
      <div v-if="viewMode === 'tree'">
        <el-table
            :data="categoryTree"
            v-loading="loading"
            row-key="categoryId"
            :tree-props="{ children: 'children' }"
        >
          <el-table-column prop="categoryName" label="分类名称" />
          <el-table-column prop="parentId" label="父级ID">
            <template #default="{ row }">
              {{ row.parentId || '根分类' }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" />
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 表格视图 -->
      <div v-if="viewMode === 'table'">
        <el-table :data="tableData" v-loading="loading">
          <el-table-column prop="categoryId" label="ID" width="80" />
          <el-table-column prop="categoryName" label="分类名称" />
          <el-table-column prop="parentId" label="父级ID">
            <template #default="{ row }">
              {{ row.parentId || '根分类' }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" />
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
              v-model:current-page="pageParams.page"
              v-model:page-size="pageParams.pageSize"
              :total="total"
              @current-change="handlePageChange"
              @size-change="handleSizeChange"
              layout="total, sizes, prev, pager, next, jumper"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted,watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { herbCategoryApi } from '@/api/admin'

const router = useRouter()
const loading = ref(false)
const showSearch = ref(false)
const viewMode = ref('tree') // tree or table
const categoryTree = ref([])
const tableData = ref([])
const total = ref(0)

const searchForm = reactive({
  categoryName: ''
})

const pageParams = reactive({
  page: 1,
  pageSize: 10
})

const loadCategoryTree = async () => {
  loading.value = true
  try {
    const res = await herbCategoryApi.getTree()
    categoryTree.value = res.data || []
  } catch (error) {
    ElMessage.error('加载分类数据失败')
  } finally {
    loading.value = false
  }
}

const loadTableData = async () => {
  loading.value = true
  try {
    const res = await herbCategoryApi.page(
        searchForm.categoryName,
        pageParams.page,
        pageParams.pageSize
    )
    tableData.value = res.data.records || []
    total.value = res.data.total || 0
  } catch (error) {
    ElMessage.error('加载分类数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pageParams.page = 1
  if (viewMode.value === 'table') {
    loadTableData()
  }
}

const handleReset = () => {
  searchForm.categoryName = ''
  pageParams.page = 1
  if (viewMode.value === 'table') {
    loadTableData()
  }
}

const toggleSearch = () => {
  showSearch.value = !showSearch.value
}

const handleAdd = () => {
  router.push('/admin/herb-category/add')
}

const handleEdit = (row) => {
  router.push(`/admin/herb-category/edit/${row.categoryId}`)
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除分类"${row.categoryName}"吗？此操作不可恢复。`,
        '警告',
        { type: 'warning' }
    )

    await herbCategoryApi.delete(row.categoryId)
    ElMessage.success('删除成功')
    // 根据当前视图模式刷新数据
    if (viewMode.value === 'tree') {
      loadCategoryTree()
    } else {
      loadTableData()
    }
  } catch (error) {
    // 用户取消操作
  }
}

const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

const handlePageChange = () => {
  loadTableData()
}

const handleSizeChange = () => {
  pageParams.page = 1
  loadTableData()
}

// 监听视图模式变化
watch(viewMode, (newVal) => {
  if (newVal === 'tree') {
    loadCategoryTree()
  } else {
    loadTableData()
  }
})

onMounted(() => {
  loadCategoryTree()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
